from machine import Timer

from log import Log, DEBUG

log = Log(tag='Timer', level=DEBUG)
SYSTEM_TIMER = Timer(-1)


class TickTimer:
    def __init__(self, interval_ms=200):
        self.__interval = interval_ms
        self.__tasks = []

    def do_task(self):
        for task in self.__tasks:
            result = True
            try:
                result = task()
            except Exception as e:
                log.warn('Error On Run Task [%s],[%s]' % (task, e))
            #  raise e
            if not result:
                log.info('task %s remove success!' % task)
                self.__tasks.remove(task)

    def __callback_fn(self):
        this = self

        def callback(_):
            this.do_task()

        return callback

    def add_task(self, task):
        self.__tasks.append(task)
        log.debug('task %s add success!' % task)
        if hasattr(task, 'setup'):
            task.setup()

    def start(self):
        SYSTEM_TIMER.init(period=self.__interval, mode=Timer.PERIODIC, callback=self.__callback_fn())

    def stop(self):
        SYSTEM_TIMER.deinit()
